<template>
  <div class="user-manager-container">
    <el-card class="filter-card">
      <div class="filter-container">
        <el-input
          v-model="queryParams.keyword"
          placeholder="搜索用户名/学号/邮箱"
          clearable
          style="width: 250px"
          @keyup.enter="handleSearch"
        />
        <el-select v-model="queryParams.role" placeholder="角色" clearable style="width: 120px">
          <el-option label="学生" value="学生" />
          <el-option label="教师" value="教师" />
          <el-option label="管理员" value="管理员" />
        </el-select>
        <el-button type="primary" @click="handleSearch">
          <el-icon><search /></el-icon>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <el-icon><refresh /></el-icon>
          重置
        </el-button>
      </div>
    </el-card>

    <!-- 待审核用户卡片 -->
    <el-card class="pending-card" v-if="pendingUsers.length > 0">
      <template #header>
        <div class="card-header">
          <span class="header-title">待审核账号</span>
          <span class="count-badge">{{ pendingUsers.length }}</span>
        </div>
      </template>
      <el-table :data="pendingUsers" style="width: 100%" border fit>
        <el-table-column prop="username" label="用户名" min-width="100" />
        <el-table-column prop="studentNumber" label="学号/工号" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="role" label="角色" min-width="90">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ getRoleName(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" min-width="150">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="180" fixed="right">
          <template #default="scope">
            <el-button type="success" size="small" @click="handleApprove(scope.row, true)">
              通过
            </el-button>
            <el-button type="danger" size="small" @click="handleApprove(scope.row, false)">
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户列表表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">用户管理</span>
        </div>
      </template>
      <el-table v-loading="loading" :data="userList" style="width: 100%" border fit>
        <el-table-column prop="username" label="用户名" min-width="100" />
        <el-table-column prop="studentNumber" label="学号/工号" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="role" label="角色" min-width="90">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ getRoleName(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" min-width="150">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="240" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
            <el-button type="warning" size="small" @click="handleResetPassword(scope.row)">
              重置密码
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户信息" width="500px">
      <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" disabled />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" style="width: 100%">
            <el-option label="学生" value="学生" />
            <el-option label="教师" value="教师" />
            <el-option label="管理员" value="管理员" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="submitting"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      :title="approveForm.approved ? '通过审核' : '拒绝审核'"
      width="500px"
    >
      <el-form :model="approveForm" ref="approveFormRef" label-width="80px">
        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="approveForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button
            :type="approveForm.approved ? 'success' : 'danger'"
            @click="submitApprove"
            :loading="submitting"
          >
            {{ approveForm.approved ? '通过' : '拒绝' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码结果对话框 -->
    <el-dialog v-model="resetDialogVisible" title="密码重置成功" width="400px" center>
      <div class="reset-password-container">
        <p>新密码已生成，请妥善保管并通知用户：</p>
        <div class="new-password">{{ newPassword }}</div>
      </div>
      <template #footer>
        <el-button type="primary" @click="resetDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  getUserList,
  getPendingUsers,
  approveUser,
  updateUser,
  resetUserPassword,
  deleteUser,
  type UserInfo,
  type UserListParams,
  type UserUpdateRequest,
  type UserApprovalRequest,
} from '@/api/admin'

// 用户列表相关数据
const userList = ref<UserInfo[]>([])
const total = ref(0)
const loading = ref(false)
const queryParams = reactive<UserListParams>({
  current: 1,
  size: 10,
  keyword: '',
  role: '',
})

// 待审核用户列表
const pendingUsers = ref<UserInfo[]>([])

// 编辑用户相关
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive<UserUpdateRequest>({
  userId: 0,
  username: '',
  phone: '',
  email: '',
  role: '',
})

// 审核相关
const approveDialogVisible = ref(false)
const approveFormRef = ref<FormInstance>()
const approveForm = reactive<UserApprovalRequest>({
  userId: 0,
  approved: true,
  remark: '',
})

// 重置密码相关
const resetDialogVisible = ref(false)
const newPassword = ref('')

// 提交状态
const submitting = ref(false)

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
    .replace(/\//g, '-')
}

// 获取角色标签类型
const getRoleTagType = (role: string) => {
  const typeMap: Record<string, string> = {
    管理员: 'danger',
    教师: 'warning',
    学生: 'success',
  }
  return typeMap[role] || ''
}

// 获取角色名称 (由于后端已经是中文，此函数可能不再需要转换，但保留以便处理其他情况)
const getRoleName = (role: string) => {
  return role
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const res = await getUserList(queryParams)
    if (res.code === 200) {
      userList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取待审核用户列表
const fetchPendingUsers = async () => {
  try {
    const res = await getPendingUsers()
    if (res.code === 200) {
      pendingUsers.value = res.data || []
    }
  } catch (error) {
    console.error('获取待审核用户失败', error)
    ElMessage.error('获取待审核用户失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  fetchUserList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.role = ''
  queryParams.current = 1
  fetchUserList()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  queryParams.size = size
  fetchUserList()
}

// 页码变化
const handleCurrentChange = (page: number) => {
  queryParams.current = page
  fetchUserList()
}

// 点击编辑按钮
const handleEdit = (row: UserInfo) => {
  Object.assign(editForm, {
    userId: row.id,
    username: row.username,
    phone: row.phone,
    email: row.email,
    role: row.role,
  })
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const res = await updateUser(editForm)

        if (res.code === 200) {
          ElMessage.success('更新成功')
          editDialogVisible.value = false
          fetchUserList()
        }
      } catch (error) {
        console.error('更新用户信息失败', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 点击审核按钮
const handleApprove = (row: UserInfo, isApproved: boolean) => {
  approveForm.userId = row.id
  approveForm.approved = isApproved
  approveForm.remark = ''
  approveDialogVisible.value = true
}

// 提交审核
const submitApprove = async () => {
  submitting.value = true
  try {
    const res = await approveUser(approveForm)

    if (res.code === 200) {
      ElMessage.success(approveForm.approved ? '已通过审核' : '已拒绝审核')
      approveDialogVisible.value = false
      fetchPendingUsers()
    }
  } catch (error) {
    console.error('审核操作失败', error)
  } finally {
    submitting.value = false
  }
}

// 重置密码
const handleResetPassword = (row: UserInfo) => {
  ElMessageBox.confirm('确定要重置该用户的密码吗？系统将生成一个新的随机密码。', '重置密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await resetUserPassword(row.id)

        if (res.code === 200) {
          newPassword.value = res.data
          resetDialogVisible.value = true
        }
      } catch (error) {
        console.error('重置密码失败', error)
        ElMessage.error('重置密码失败')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 删除用户
const handleDelete = (row: UserInfo) => {
  ElMessageBox.confirm('确定要删除该用户吗？此操作不可恢复！', '删除用户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(async () => {
      try {
        const res = await deleteUser(row.id)

        if (res.code === 200) {
          ElMessage.success('删除成功')
          fetchUserList()
        }
      } catch (error) {
        console.error('删除用户失败', error)
        ElMessage.error('删除用户失败')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

onMounted(() => {
  fetchUserList()
  fetchPendingUsers()
})
</script>

<style scoped>
.user-manager-container {
  padding: 20px;
  width: 100%;
  max-width: 100%;
}

.filter-card,
.pending-card,
.table-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.card-header {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: bold;
}

.count-badge {
  margin-left: 10px;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 2px 8px;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.reset-password-container {
  text-align: center;
  padding: 10px 0;
}

.new-password {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  margin: 15px 0;
  padding: 10px;
  background-color: #f7f7f7;
  border-radius: 5px;
}

/* 修改表格相关样式 */
:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-card__body) {
  padding: 10px;
}

/* 调整列宽度以适应内容，让表格占据更多空间 */
:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
}
</style>
